package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import com.zzyl.constant.Constants;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {
    
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是处理器对象
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //如果是拦截器对象就校验token
        //获取请求头中的token
        String token = request.getHeader("authorization");
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretkey(), token);
//        String memberId = claims.getId();

        //将String类型的变量转成long类型
//        Long l = Long.valueOf(claims.get(Constants.JWT_USERID).toString());
        //这个工具类是将对象中的属性取出来，然后转成指定的类型
        Long memberId = MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        log.info("登录用户的id为：{}",memberId);
        UserThreadLocal.set(memberId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}